home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / p_man / cat3 / overload.Z / overload
Encoding:
Text File  |  1998-10-28  |  50.8 KB  |  1,453 lines

  1.  
  2.  
  3.  
  4.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       overload - Package for overloading perl operations
  10.  
  11.      SSSSYYYYNNNNOOOOPPPPSSSSIIIISSSS
  12.           package SomeThing;
  13.  
  14.           use overload
  15.           '+' => \&myadd,
  16.           '-' => \&mysub;
  17.           # etc
  18.           ...
  19.  
  20.           package main;
  21.           $a = new SomeThing 57;
  22.           $b=5+$a;
  23.           ...
  24.           if (overload::Overloaded $b) {...}
  25.           ...
  26.           $strval =    overload::StrVal $b;
  27.  
  28.  
  29.      CCCCAAAAVVVVEEEEAAAATTTT SSSSCCCCRRRRIIIIPPPPTTTTOOOORRRR
  30.       Overloading of operators is a    subject    not to be taken
  31.       lightly.  Neither its    precise    implementation,    syntax,    nor
  32.       semantics are    100% endorsed by Larry Wall.  So any of    these
  33.       may be changed at some point in the future.
  34.  
  35.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  36.       DDDDeeeeccccllllaaaarrrraaaattttiiiioooonnnn ooooffff oooovvvveeeerrrrllllooooaaaaddddeeeedddd ffffuuuunnnnccccttttiiiioooonnnnssss
  37.  
  38.       The compilation directive
  39.  
  40.           package Number;
  41.           use overload
  42.           "+" => \&add,
  43.           "*=" => "muas";
  44.  
  45.       declares function _N_u_m_b_e_r::_a_d_d() for addition,    and method
  46.       _m_u_a_s() in the    "class"    Number (or one of its base classes)
  47.       for the assignment form *= of    multiplication.
  48.  
  49.       Arguments of this directive come in (key, value) pairs.
  50.       Legal    values are values legal    inside a &{ ...    } call,    so the
  51.       name of a subroutine,    a reference to a subroutine, or    an
  52.       anonymous subroutine will all    work.  Note that values
  53.       specified as strings are interpreted as methods, not
  54.       subroutines.    Legal keys are listed below.
  55.  
  56.       The subroutine add will be called to execute $a+$b if    $a is
  57.       a reference to an object blessed into    the package Number, or
  58.       if $a    is not an object from a    package    with defined
  59.       mathemagic addition, but $b is a reference to    a Number.  It
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  71.  
  72.  
  73.  
  74.       can also be called in    other situations, like $a+=7, or $a++.
  75.       See the section on _M_A_G_I_C _A_U_T_O_G_E_N_E_R_A_T_I_O_N.  (Mathemagical
  76.       methods refer    to methods triggered by    an overloaded
  77.       mathematical operator.)
  78.  
  79.       Since    overloading respects inheritance via the @ISA
  80.       hierarchy, the above declaration would also trigger
  81.       overloading of + and *= in all the packages which inherit
  82.       from Number.
  83.  
  84.       CCCCaaaalllllllliiiinnnngggg CCCCoooonnnnvvvveeeennnnttttiiiioooonnnnssss ffffoooorrrr BBBBiiiinnnnaaaarrrryyyy OOOOppppeeeerrrraaaattttiiiioooonnnnssss
  85.  
  86.       The functions    specified in the use overload ... directive
  87.       are called with three    (in one    particular case    with four, see
  88.       the section on _L_a_s_t _R_e_s_o_r_t) arguments.  If the corresponding
  89.       operation is binary, then the    first two arguments are    the
  90.       two arguments    of the operation.  However, due    to general
  91.       object calling conventions, the first    argument should    always
  92.       be an    object in the package, so in the situation of 7+$a,
  93.       the order of the arguments is    interchanged.  It probably
  94.       does not matter when implementing the    addition method, but
  95.       whether the arguments    are reversed is    vital to the
  96.       subtraction method.  The method can query this information
  97.       by examining the third argument, which can take three
  98.       different values:
  99.  
  100.       FALSE     the order of arguments    is as in the current
  101.          operation.
  102.  
  103.       TRUE     the arguments are reversed.
  104.  
  105.       undef     the current operation is an assignment    variant    (as in
  106.          $a+=7), but the usual function    is called instead.
  107.          This additional information can be used to generate
  108.          some optimizations.  Compare the section on _C_a_l_l_i_n_g
  109.          _C_o_n_v_e_n_t_i_o_n_s _f_o_r _M_u_t_a_t_o_r_s.
  110.  
  111.       CCCCaaaalllllllliiiinnnngggg CCCCoooonnnnvvvveeeennnnttttiiiioooonnnnssss ffffoooorrrr UUUUnnnnaaaarrrryyyy    OOOOppppeeeerrrraaaattttiiiioooonnnnssss
  112.  
  113.       Unary    operation are considered binary    operations with    the
  114.       second argument being    undef.    Thus the functions that
  115.       overloads {"++"} is called with arguments ($a,undef,'') when
  116.       $a++ is executed.
  117.  
  118.       CCCCaaaalllllllliiiinnnngggg CCCCoooonnnnvvvveeeennnnttttiiiioooonnnnssss ffffoooorrrr MMMMuuuuttttaaaattttoooorrrrssss
  119.  
  120.       Two types of mutators    have different calling conventions:
  121.  
  122.       ++ and --
  123.            The routines which implement these operators are
  124.            expected    to actually _m_u_t_a_t_e their arguments.  So,
  125.            assuming    that $obj is a reference to a number,
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  137.  
  138.  
  139.  
  140.          sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
  141.  
  142.            is an appropriate implementation    of overloaded ++.
  143.            Note that
  144.  
  145.          sub incr { ++$    {$_[0]}    ; shift    }
  146.  
  147.            is OK if    used with preincrement and with    postincrement.
  148.            (In the case of postincrement a copying will be
  149.            performed, see the section on _C_o_p_y _C_o_n_s_t_r_u_c_t_o_r.)
  150.  
  151.       x= and other assignment versions
  152.            There is    nothing    special    about these methods.  They may
  153.            change the value    of their arguments, and    may leave it
  154.            as is.  The result is going to be assigned to the value
  155.            in the left-hand-side if    different from this value.
  156.  
  157.            This allows for the same    method to be used as
  158.            averloaded += and +.  Note that this is _a_l_l_o_w_e_d,    but
  159.            not recommended,    since by the semantic of the section
  160.            on _F_a_l_l_b_a_c_k Perl    will call the method for + anyway, if
  161.            += is not overloaded.
  162.  
  163.       WWWWaaaarrrrnnnniiiinnnngggg....  Due    to the presense    of assignment versions of
  164.       operations, routines which may be called in assignment
  165.       context may create self-referencial structures.  Currently
  166.       Perl will not    free self-referential structures until cycles
  167.       are explicitly broken.  You may get problems when traversing
  168.       your structures too.
  169.  
  170.       Say,
  171.  
  172.         use    overload '+' =>    sub { bless [ \$_[0], \$_[1] ] };
  173.  
  174.       is asking for    trouble, since for code    $obj +=    $foo the
  175.       subroutine is    called as $obj = add($obj, $foo, undef), or
  176.       $obj = [\$obj, \$foo].  If using such    a subroutine is    an
  177.       important optimization, one can overload += explicitly by a
  178.       non-"optimized" version, or switch to    non-optimized version
  179.       if not defined $_[2] (see the    section    on _C_a_l_l_i_n_g _C_o_n_v_e_n_t_i_o_n_s
  180.       _f_o_r _B_i_n_a_r_y _O_p_e_r_a_t_i_o_n_s).
  181.  
  182.       Even if no _e_x_p_l_i_c_i_t assignment-variants of operators are
  183.       present in the script, they may be generated by the
  184.       optimizer.  Say, ",$obj," or ',' . $obj . ','    may be both
  185.       optimized to
  186.  
  187.         my $tmp = ',' . $obj;    $tmp .= ',';
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  203.  
  204.  
  205.  
  206.       OOOOvvvveeeerrrrllllooooaaaaddddaaaabbbblllleeee OOOOppppeeeerrrraaaattttiiiioooonnnnssss
  207.  
  208.       The following    symbols    can be specified in use    overload
  209.       directive:
  210.  
  211.       +o _A_r_i_t_h_m_e_t_i_c _o_p_e_r_a_t_i_o_n_s
  212.  
  213.            "+",    "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
  214.            "**", "**=",    "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
  215.  
  216.            For these operations a substituted non-assignment
  217.            variant can be called if    the assignment variant is not
  218.            available.  Methods for operations "+", "-", "+=", and
  219.            "-=" can    be called to automatically generate increment
  220.            and decrement methods.  The operation "-" can be    used
  221.            to autogenerate missing methods for unary minus or abs.
  222.  
  223.            See the section on _M_A_G_I_C    _A_U_T_O_G_E_N_E_R_A_T_I_O_N,    the section on
  224.            _C_a_l_l_i_n_g _C_o_n_v_e_n_t_i_o_n_s _f_o_r _M_u_t_a_t_o_r_s    and the    section    on
  225.            _C_a_l_l_i_n_g _C_o_n_v_e_n_t_i_o_n_s _f_o_r _B_i_n_a_r_y _O_p_e_r_a_t_i_o_n_s) for details
  226.            of these    substitutions.
  227.  
  228.       +o _C_o_m_p_a_r_i_s_o_n _o_p_e_r_a_t_i_o_n_s
  229.  
  230.            "<",     "<=", ">",  ">=", "==", "!=", "<=>",
  231.            "lt", "le", "gt", "ge", "eq", "ne", "cmp",
  232.  
  233.            If the corresponding "spaceship"    variant    is available,
  234.            it can be used to substitute for    the missing operation.
  235.            During sorting arrays, cmp is used to compare values
  236.            subject to use overload.
  237.  
  238.       +o _B_i_t    _o_p_e_r_a_t_i_o_n_s
  239.  
  240.            "&",    "^", "|", "neg", "!", "~",
  241.  
  242.            "neg" stands for    unary minus.  If the method for    neg is
  243.            not specified, it can be    autogenerated using the    method
  244.            for subtraction.    If the method for "!" is not
  245.            specified, it can be autogenerated using    the methods
  246.            for "bool", or "\"\"", or "0+".
  247.  
  248.       +o _I_n_c_r_e_m_e_n_t _a_n_d _d_e_c_r_e_m_e_n_t
  249.  
  250.            "++", "--",
  251.  
  252.            If undefined, addition and subtraction methods can be
  253.            used instead.  These operations are called both in
  254.            prefix and postfix form.
  255.  
  256.       +o _T_r_a_n_s_c_e_n_d_e_n_t_a_l _f_u_n_c_t_i_o_n_s
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  269.  
  270.  
  271.  
  272.            "atan2", "cos", "sin", "exp", "abs",    "log", "sqrt",
  273.  
  274.            If abs is unavailable, it can be    autogenerated using
  275.            methods for "<" or "<=>"    combined with either unary
  276.            minus or    subtraction.
  277.  
  278.       +o _B_o_o_l_e_a_n, _s_t_r_i_n_g _a_n_d    _n_u_m_e_r_i_c    _c_o_n_v_e_r_s_i_o_n
  279.  
  280.            "bool", "\"\"", "0+",
  281.  
  282.            If one or two of    these operations are unavailable, the
  283.            remaining ones can be used instead.  bool is used in
  284.            the flow    control    operators (like    while) and for the
  285.            ternary "?:" operation.    These functions    can return any
  286.            arbitrary Perl value.  If the corresponding operation
  287.            for this    value is overloaded too, that operation    will
  288.            be called again with this value.
  289.  
  290.       +o _S_p_e_c_i_a_l
  291.  
  292.            "nomethod", "fallback", "=",
  293.  
  294.            see the section on _S_P_E_C_I_A_L _S_Y_M_B_O_L_S _F_O_R _u_s_e _o_v_e_r_l_o_a_d.
  295.  
  296.       See the section on _F_a_l_l_b_a_c_k for an explanation of when a
  297.       missing method can be    autogenerated.
  298.  
  299.       A computer-readable form of the above    table is available in
  300.       the hash %overload::ops, with    values being space-separated
  301.       lists    of names:
  302.  
  303.        with_assign        => '+ - * /    % ** <<    >> x .',
  304.        assign        => '+= -= *= /= %= **= <<= >>= x= .=',
  305.        str_comparison   => '< <= > >= == !=',
  306.        '3way_comparison'=> '<=> cmp',
  307.        num_comparison   => 'lt le gt ge eq ne',
  308.        binary        => '& | ^',
  309.        unary        => 'neg ! ~',
  310.        mutators        => '++ --',
  311.        func            => 'atan2 cos sin exp abs log sqrt',
  312.        conversion        => 'bool ""    0+',
  313.        special        => 'nomethod fallback ='
  314.  
  315.  
  316.       IIIInnnnhhhheeeerrrriiiittttaaaannnncccceeee aaaannnndddd oooovvvveeeerrrrllllooooaaaaddddiiiinnnngggg
  317.  
  318.       Inheritance interacts    with overloading in two    ways.
  319.  
  320.       Strings as values of use overload directive
  321.            If value    in
  322.  
  323.          use overload key => value;
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  335.  
  336.  
  337.  
  338.            is a string, it is interpreted as a method name.
  339.  
  340.       Overloading of an operation is inherited by derived classes
  341.            Any class derived from an overloaded class is also
  342.            overloaded.  The    set of overloaded methods is the union
  343.            of overloaded methods of    all the    ancestors. If some
  344.            method is overloaded in several ancestor, then which
  345.            description will    be used    is decided by the usual
  346.            inheritance rules:
  347.  
  348.            If A inherits from B and    C (in this order), B overloads
  349.            + with \&D::plus_sub, and C overloads + by "plus_meth",
  350.            then the    subroutine D::plus_sub will be called to
  351.            implement operation + for an object in package A.
  352.  
  353.       Note that since the value of the fallback key    is not a
  354.       subroutine, its inheritance is not governed by the above
  355.       rules.  In the current implementation, the value of fallback
  356.       in the first overloaded ancestor is used, but    this is
  357.       accidental and subject to change.
  358.  
  359.      SSSSPPPPEEEECCCCIIIIAAAALLLL SSSSYYYYMMMMBBBBOOOOLLLLSSSS FFFFOOOORRRR uuuusssseeee oooovvvveeeerrrrllllooooaaaadddd
  360.       Three    keys are recognized by Perl that are not covered by
  361.       the above description.
  362.  
  363.       LLLLaaaasssstttt RRRReeeessssoooorrrrtttt
  364.  
  365.       "nomethod" should be followed    by a reference to a function
  366.       of four parameters.  If defined, it is called    when the
  367.       overloading mechanism    cannot find a method for some
  368.       operation.  The first    three arguments    of this    function
  369.       coincide with    the arguments for the corresponding method if
  370.       it were found, the fourth argument is    the symbol
  371.       corresponding    to the missing method.    If several methods are
  372.       tried, the last one is used.    Say, 1-$a can be equivalent to
  373.  
  374.           &nomethodMethod($a,1,1,"-")
  375.  
  376.       if the pair "nomethod" => "nomethodMethod" was specified in
  377.       the use overload directive.
  378.  
  379.       If some operation cannot be resolved,    and there is no
  380.       function assigned to "nomethod", then    an exception will be
  381.       raised via _d_i_e()-- unless "fallback" was specified as    a key
  382.       in use overload directive.
  383.  
  384.       FFFFaaaallllllllbbbbaaaacccckkkk
  385.  
  386.       The key "fallback" governs what to do    if a method for    a
  387.       particular operation is not found.  Three different cases
  388.       are possible depending on the    value of "fallback":
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  401.  
  402.  
  403.  
  404.       +o undef      Perl tries to    use a substituted method (see
  405.               the section on _M_A_G_I_C _A_U_T_O_G_E_N_E_R_A_T_I_O_N).     If
  406.               this fails, it then tries to calls
  407.               "nomethod" value; if missing,    an exception
  408.               will be raised.
  409.  
  410.       +o TRUE      The same as for the undef value, but no
  411.               exception is raised.    Instead, it silently
  412.               reverts to what it would have    done were
  413.               there    no use overload    present.
  414.  
  415.       +o defined, but FALSE
  416.               No autogeneration is tried.  Perl tries to
  417.               call "nomethod" value, and if    this is
  418.               missing, raises an exception.
  419.  
  420.       NNNNooootttteeee....    "fallback" inheritance via @ISA    is not carved in stone
  421.       yet, see the section on _I_n_h_e_r_i_t_a_n_c_e _a_n_d _o_v_e_r_l_o_a_d_i_n_g.
  422.  
  423.       CCCCooooppppyyyy CCCCoooonnnnssssttttrrrruuuuccccttttoooorrrr
  424.  
  425.       The value for    "=" is a reference to a    function with three
  426.       arguments, i.e., it looks like the other values in use
  427.       overload. However, it    does not overload the Perl assignment
  428.       operator. This would go against Camel    hair.
  429.  
  430.       This operation is called in the situations when a mutator is
  431.       applied to a reference that shares its object    with some
  432.       other    reference, such    as
  433.  
  434.           $a=$b;
  435.           ++$a;
  436.  
  437.       To make this change $a and not change    $b, a copy of $$a is
  438.       made,    and $a is assigned a reference to this new object.
  439.       This operation is done during    execution of the ++$a, and not
  440.       during the assignment, (so before the    increment $$a
  441.       coincides with $$b).    This is    only done if ++    is expressed
  442.       via a    method for '++'    or '+='    (or nomethod).    Note that if
  443.       this operation is expressed via '+' a    nonmutator, i.e., as
  444.       in
  445.  
  446.           $a=$b;
  447.           $a=$a+1;
  448.  
  449.       then $a does not reference a new copy    of $$a,    since $$a does
  450.       not appear as    lvalue when the    above code is executed.
  451.  
  452.       If the copy constructor is required during the execution of
  453.       some mutator,    but a method for '=' was not specified,    it can
  454.       be autogenerated as a    string copy if the object is a plain
  455.       scalar.
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  467.  
  468.  
  469.  
  470.       EEEExxxxaaaammmmpppplllleeee
  471.            The actually executed code for
  472.  
  473.                $a=$b;
  474.                Something else which does not modify $a or $b....
  475.                ++$a;
  476.  
  477.            may be
  478.  
  479.                $a=$b;
  480.                Something else which does not modify $a or $b....
  481.                $a = $a->clone(undef,"");
  482.                $a->incr(undef,"");
  483.  
  484.            if $b was mathemagical, and '++'    was overloaded with
  485.            \&incr, '=' was overloaded with \&clone.
  486.  
  487.       Same behaviour is triggered by $b = $a++, which is consider
  488.       a synonim for    $b = $a; ++$a.
  489.  
  490.      MMMMAAAAGGGGIIIICCCC AAAAUUUUTTTTOOOOGGGGEEEENNNNEEEERRRRAAAATTTTIIIIOOOONNNN
  491.       If a method for an operation is not found, and the value for
  492.       "fallback" is    TRUE or    undefined, Perl    tries to autogenerate
  493.       a substitute method for the missing operation    based on the
  494.       defined operations.  Autogenerated method substitutions are
  495.       possible for the following operations:
  496.  
  497.       _A_s_s_i_g_n_m_e_n_t _f_o_r_m_s _o_f _a_r_i_t_h_m_e_t_i_c _o_p_e_r_a_t_i_o_n_s
  498.               $a+=$b can use the method for    "+" if the
  499.               method for "+=" is not defined.
  500.  
  501.       _C_o_n_v_e_r_s_i_o_n _o_p_e_r_a_t_i_o_n_s
  502.               String, numeric, and boolean conversion are
  503.               calculated in    terms of one another if    not
  504.               all of them are defined.
  505.  
  506.       _I_n_c_r_e_m_e_n_t _a_n_d    _d_e_c_r_e_m_e_n_t
  507.               The ++$a operation can be expressed in terms
  508.               of $a+=1 or $a+1, and    $a-- in    terms of $a-=1
  509.               and $a-1.
  510.  
  511.       abs($a)      can be expressed in terms of $a<0 and    -$a
  512.               (or 0-$a).
  513.  
  514.       _U_n_a_r_y    _m_i_n_u_s      can be expressed in terms of subtraction.
  515.  
  516.       _N_e_g_a_t_i_o_n      ! and    not can    be expressed in    terms of
  517.               boolean conversion, or string    or numerical
  518.               conversion.
  519.  
  520.       _C_o_n_c_a_t_e_n_a_t_i_o_n      can be expressed in terms of string
  521.               conversion.
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  533.  
  534.  
  535.  
  536.       _C_o_m_p_a_r_i_s_o_n _o_p_e_r_a_t_i_o_n_s
  537.               can be expressed in terms of its "spaceship"
  538.               counterpart: either <=> or cmp:
  539.  
  540.                   <, >, <=,    >=, ==,    !=      in terms of <=>
  541.                   lt, gt, le, ge, eq, ne      in terms of cmp
  542.  
  543.  
  544.       _C_o_p_y _o_p_e_r_a_t_o_r      can be expressed in terms of an assignment
  545.               to the dereferenced value, if    this value is
  546.               a scalar and not a reference.
  547.  
  548.      LLLLoooossssiiiinnnngggg oooovvvveeeerrrrllllooooaaaaddddiiiinnnngggg
  549.       The restriction for the comparison operation is that even
  550.       if, for example, `cmp' should    return a blessed reference,
  551.       the autogenerated `lt' function will produce only a standard
  552.       logical value    based on the numerical value of    the result of
  553.       `cmp'.  In particular, a working numeric conversion is
  554.       needed in this case (possibly    expressed in terms of other
  555.       conversions).
  556.  
  557.       Similarly, .=     and x=    operators lose their mathemagical
  558.       properties if    the string conversion substitution is applied.
  559.  
  560.       When you _c_h_o_p() a mathemagical object    it is promoted to a
  561.       string and its mathemagical properties are lost.  The    same
  562.       can happen with other    operations as well.
  563.  
  564.      RRRRuuuunnnn----ttttiiiimmmmeeee OOOOvvvveeeerrrrllllooooaaaaddddiiiinnnngggg
  565.       Since    all use    directives are executed    at compile-time, the
  566.       only way to change overloading during    run-time is to
  567.  
  568.           eval 'use    overload "+" =>    \&addmethod';
  569.  
  570.       You can also use
  571.  
  572.           eval 'no overload    "+", "--", "<="';
  573.  
  574.       though the use of these constructs during run-time is
  575.       questionable.
  576.  
  577.      PPPPuuuubbbblllliiiicccc ffffuuuunnnnccccttttiiiioooonnnnssss
  578.       Package overload.pm provides the following public functions:
  579.  
  580.       overload::StrVal(arg)
  581.            Gives string value of arg as in absence of stringify
  582.            overloading.
  583.  
  584.       overload::Overloaded(arg)
  585.            Returns true if arg is subject to overloading of    some
  586.            operations.
  587.  
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  599.  
  600.  
  601.  
  602.       overload::Method(obj,op)
  603.            Returns undef or    a reference to the method that
  604.            implements op.
  605.  
  606.      OOOOvvvveeeerrrrllllooooaaaaddddiiiinnnngggg ccccoooonnnnssssttttaaaannnnttttssss
  607.       For some application Perl parser mangles constants too much.
  608.       It is    possible to hook into this process via
  609.       _o_v_e_r_l_o_a_d::_c_o_n_s_t_a_n_t() and _o_v_e_r_l_o_a_d::_r_e_m_o_v_e__c_o_n_s_t_a_n_t()
  610.       functions.
  611.  
  612.       These    functions take a hash as an argument.  The recognized
  613.       keys of this hash are
  614.  
  615.       integer to overload integer constants,
  616.  
  617.       float      to overload floating point constants,
  618.  
  619.       binary  to overload octal and    hexadecimal constants,
  620.  
  621.       q      to overload q-quoted strings,    constant pieces    of qq-
  622.           and qx-quoted    strings    and here-documents,
  623.  
  624.       qr      to overload constant pieces of regular expressions.
  625.  
  626.       The corresponding values are references to functions which
  627.       take three arguments:     the first one is the _i_n_i_t_i_a_l string
  628.       form of the constant,    the second one is how Perl interprets
  629.       this constant, the third one is how the constant is used.
  630.       Note that the    initial    string form does not contain string
  631.       delimiters, and has backslashes in backslash-delimiter
  632.       combinations stripped    (thus the value    of delimiter is    not
  633.       relevant for processing of this string).  The    return value
  634.       of this function is how this constant    is going to be
  635.       interpreted by Perl.    The third argument is undefined    unless
  636.       for overloaded q- and    qr- constants, it is q in single-quote
  637.       context (comes from strings, regular expressions, and
  638.       single-quote HERE documents),    it is tr for arguments of tr/y
  639.       operators, it    is s for right-hand side of s-operator,    and it
  640.       is qq    otherwise.
  641.  
  642.       Since    an expression "ab$cd,,"    is just    a shortcut for 'ab' .
  643.       $cd .    ',,', it is expected that overloaded constant strings
  644.       are equipped with reasonable overloaded catenation operator,
  645.       otherwise absurd results will    result.    Similarly, negative
  646.       numbers are considered as negations of positive constants.
  647.  
  648.       Note that it is probably meaningless to call the functions
  649.       _o_v_e_r_l_o_a_d::_c_o_n_s_t_a_n_t() and _o_v_e_r_l_o_a_d::_r_e_m_o_v_e__c_o_n_s_t_a_n_t() from
  650.       anywhere but _i_m_p_o_r_t()    and _u_n_i_m_p_o_r_t() methods.     From these
  651.       methods they may be called as
  652.  
  653.  
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  665.  
  666.  
  667.  
  668.           sub import {
  669.             shift;
  670.             return unless @_;
  671.             die    "unknown import: @_" unless @_ == 1 and    $_[0] eq ':constant';
  672.             overload::constant integer => sub {Math::BigInt->new(shift)};
  673.           }
  674.  
  675.       BBBBUUUUGGGGSSSS Currently overloaded-ness of constants does not
  676.       propagate into eval '...'.
  677.  
  678.      IIIIMMMMPPPPLLLLEEEEMMMMEEEENNNNTTTTAAAATTTTIIIIOOOONNNN
  679.       What follows is subject to change RSN.
  680.  
  681.       The table of methods for all operations is cached in magic
  682.       for the symbol table hash for    the package.  The cache    is
  683.       invalidated during processing    of use overload, no overload,
  684.       new function definitions, and    changes    in @ISA. However, this
  685.       invalidation remains unprocessed until the next blessing
  686.       into the package. Hence if you want to change    overloading
  687.       structure dynamically, you'll    need an    additional (fake)
  688.       blessing to update the table.
  689.  
  690.       (Every SVish thing has a magic queue,    and magic is an    entry
  691.       in that queue.  This is how a    single variable    may
  692.       participate in multiple forms    of magic simultaneously.  For
  693.       instance, environment    variables regularly have two forms at
  694.       once:    their %ENV magic and their taint magic.    However, the
  695.       magic    which implements overloading is    applied    to the
  696.       stashes, which are rarely used directly, thus    should not
  697.       slow down Perl.)
  698.  
  699.       If an    object belongs to a package using overload, it carries
  700.       a special flag.  Thus    the only speed penalty during
  701.       arithmetic operations    without    overloading is the checking of
  702.       this flag.
  703.  
  704.       In fact, if use overload is not present, there is almost no
  705.       overhead for overloadable operations,    so most    programs
  706.       should not suffer measurable performance penalties.  A
  707.       considerable effort was made to minimize the overhead    when
  708.       overload is used in some package, but    the arguments in
  709.       question do not belong to packages using overload.  When in
  710.       doubt, test your speed with use overload and without it.  So
  711.       far there have been no reports of substantial    speed
  712.       degradation if Perl is compiled with optimization turned on.
  713.  
  714.       There    is no size penalty for data if overload    is not used.
  715.       The only size    penalty    if overload is used in some package is
  716.       that _a_l_l the packages    acquire    a magic    during the next
  717.       blessing into    the package. This magic    is three-words-long
  718.       for packages without overloading, and    carries    the cache
  719.       tabel    if the package is overloaded.
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  731.  
  732.  
  733.  
  734.       Copying ($a=$b) is shallow; however, a one-level-deep
  735.       copying is carried out before    any operation that can imply
  736.       an assignment    to the object $a (or $b) refers    to, like $a++.
  737.       You can override this    behavior by defining your own copy
  738.       constructor (see the section on _C_o_p_y _C_o_n_s_t_r_u_c_t_o_r).
  739.  
  740.       It is    expected that arguments    to methods that    are not
  741.       explicitly supposed to be changed are    constant (but this is
  742.       not enforced).
  743.  
  744.      MMMMeeeettttaaaapppphhhhoooorrrr ccccllllaaaasssshhhh
  745.       One may wonder why the semantic of overloaded    = is so
  746.       counterintuive.  If it _l_o_o_k_s counterintuive to you, you are
  747.       subject to a metaphor    clash.
  748.  
  749.       Here is a Perl object    metaphor:
  750.  
  751.         _o_b_j_e_c_t _i_s _a    _r_e_f_e_r_e_n_c_e _t_o _b_l_e_s_s_e_d _d_a_t_a
  752.  
  753.       and an arithmetic metaphor:
  754.  
  755.         _o_b_j_e_c_t _i_s _a    _t_h_i_n_g _b_y _i_t_s_e_l_f.
  756.  
  757.       The _m_a_i_n problem of overloading = is the fact    that these
  758.       metaphors imply different actions on the assignment $a = $b
  759.       if $a    and $b are objects.  Perl-think    implies    that $a
  760.       becomes a reference to whatever $b was referencing.
  761.       Arithmetic-think implies that    the value of "object" $a is
  762.       changed to become the    value of the object $b,    preserving the
  763.       fact that $a and $b are separate entities.
  764.  
  765.       The difference is not    relevant in the    absence    of mutators.
  766.       After    a Perl-way assignment an operation which mutates the
  767.       data referenced by $a    would change the data referenced by $b
  768.       too.    Effectively, after $a =    $b values of $a    and $b become
  769.       _i_n_d_i_s_t_i_n_g_u_i_s_h_a_b_l_e.
  770.  
  771.       On the other hand, anyone who    has used algebraic notation
  772.       knows    the expressive power of    the arithmetic metaphor.
  773.       Overloading works hard to enable this    metaphor while
  774.       preserving the Perlian way as    far as possible.  Since    it is
  775.       not not possible to freely mix two contradicting metaphors,
  776.       overloading allows the arithmetic way    to write things    _a_s _f_a_r
  777.       _a_s _a_l_l _t_h_e _m_u_t_a_t_o_r_s _a_r_e _c_a_l_l_e_d _v_i_a _o_v_e_r_l_o_a_d_e_d    _a_c_c_e_s_s _o_n_l_y.
  778.       The way it is    done is    described in the section on _C_o_p_y
  779.       _C_o_n_s_t_r_u_c_t_o_r.
  780.  
  781.       If some mutator methods are directly applied to the
  782.       overloaded values, one may need to _e_x_p_l_i_c_i_t_l_y    _u_n_l_i_n_k other
  783.       values which references the same value:
  784.  
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  797.  
  798.  
  799.  
  800.           $a = new Data 23;
  801.           ...
  802.           $b = $a;          # $b is "linked" to $a
  803.           ...
  804.           $a = $a->clone;      # Unlink $b from $a
  805.           $a->increment_by(4);
  806.  
  807.       Note that overloaded access makes this transparent:
  808.  
  809.           $a = new Data 23;
  810.           $b = $a;          # $b is "linked" to $a
  811.           $a += 4;          # would unlink $b automagically
  812.  
  813.       However, it would not    make
  814.  
  815.           $a = new Data 23;
  816.           $a = 4;          # Now    $a is a    plain 4, not 'Data'
  817.  
  818.       preserve "objectness"    of $a.    But Perl _h_a_s a way to make
  819.       assignments to an object do whatever you want.  It is    just
  820.       not the overload, but    _t_i_e()ing interface (see    the tie    entry
  821.       in the _p_e_r_l_f_u_n_c manpage).  Adding a _F_E_T_C_H() method which
  822.       returns the object itself, and _S_T_O_R_E() method    which changes
  823.       the value of the object, one can reproduce the arithmetic
  824.       metaphor in its completeness,    at least for variables which
  825.       were _t_i_e()d from the start.
  826.  
  827.       (Note    that a workaround for a    bug may    be needed, see the
  828.       section on _B_U_G_S.)
  829.  
  830.      CCCCooooooookkkkbbbbooooooookkkk
  831.       Please add examples to what follows!
  832.  
  833.       TTTTwwwwoooo----ffffaaaacccceeee ssssccccaaaallllaaaarrrrssss
  834.  
  835.       Put this in _t_w_o__f_a_c_e._p_m in your Perl library directory:
  836.  
  837.         package two_face;          # Scalars with separate string and
  838.                       # numeric values.
  839.         sub    new { my $p = shift; bless [@_], $p }
  840.         use    overload '""' => \&str,    '0+' =>    \&num, fallback    => 1;
  841.         sub    num {shift->[1]}
  842.         sub    str {shift->[0]}
  843.  
  844.       Use it as follows:
  845.  
  846.         require two_face;
  847.         my $seven =    new two_face ("vii", 7);
  848.         printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
  849.         print "seven contains `i'\n" if $seven =~ /i/;
  850.  
  851.       (The second line creates a scalar which has both a string
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  863.  
  864.  
  865.  
  866.       value, and a numeric value.)    This prints:
  867.  
  868.         seven=vii, seven=7,    eight=8
  869.         seven contains `i'
  870.  
  871.  
  872.       SSSSyyyymmmmbbbboooolllliiiicccc ccccaaaallllccccuuuullllaaaattttoooorrrr
  873.  
  874.       Put this in _s_y_m_b_o_l_i_c._p_m in your Perl library directory:
  875.  
  876.         package symbolic;          # Primitive symbolic calculator
  877.         use    overload nomethod => \&wrap;
  878.  
  879.         sub    new { shift; bless ['n', @_] }
  880.         sub    wrap {
  881.           my ($obj,    $other,    $inv, $meth) = @_;
  882.           ($obj, $other) = ($other,    $obj) if $inv;
  883.           bless [$meth, $obj, $other];
  884.         }
  885.  
  886.       This module is very unusual as overloaded modules go:    it
  887.       does not provide any usual overloaded    operators, instead it
  888.       provides the the section on _L_a_s_t _R_e_s_o_r_t operator nomethod.
  889.       In this example the corresponding subroutine returns an
  890.       object which encupsulates operations done over the objects:
  891.       new symbolic 3 contains ['n',    3], 2 +    new symbolic 3
  892.       contains ['+', 2, ['n', 3]].
  893.  
  894.       Here is an example of    the script which "calculates" the side
  895.       of circumscribed octagon using the above package:
  896.  
  897.         require symbolic;
  898.         my $iter = 1;          # 2**($iter+2) = 8
  899.         my $side = new symbolic 1;
  900.         my $cnt = $iter;
  901.  
  902.         while ($cnt--) {
  903.           $side = (sqrt(1 +    $side**2) - 1)/$side;
  904.         }
  905.         print "OK\n";
  906.  
  907.       The value of $side is
  908.  
  909.         ['/', ['-',    ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
  910.                  undef], 1], ['n', 1]]
  911.  
  912.       Note that while we obtained this value using a nice little
  913.       script, there    is no simple way to _u_s_e    this value.  In    fact
  914.       this value may be inspected in debugger (see the _p_e_r_l_d_e_b_u_g
  915.       manpage), but    ony if bareStringify OOOOption is set, and    not
  916.       via p    command.
  917.  
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  929.  
  930.  
  931.  
  932.       If one attempts to print this    value, then the    overloaded
  933.       operator "" will be called, which will call nomethod
  934.       operator.  The result    of this    operator will be stringified
  935.       again, but this result is again of type symbolic, which will
  936.       lead to an infinite loop.
  937.  
  938.       Add a    pretty-printer method to the module _s_y_m_b_o_l_i_c._p_m:
  939.  
  940.         sub    pretty {
  941.           my ($meth, $a, $b) = @{+shift};
  942.           $a = 'u' unless defined $a;
  943.           $b = 'u' unless defined $b;
  944.           $a = $a->pretty if ref $a;
  945.           $b = $b->pretty if ref $b;
  946.           "[$meth $a $b]";
  947.         }
  948.  
  949.       Now one can finish the script    by
  950.  
  951.         print "side    = ", $side->pretty, "\n";
  952.  
  953.       The method pretty is doing object-to-string conversion, so
  954.       it is    natural    to overload the    operator "" using this method.
  955.       However, inside such a method    it is not necessary to
  956.       pretty-print the _c_o_m_p_o_n_e_n_t_s $a and $b    of an object.  In the
  957.       above    subroutine "[$meth $a $b]" is a    catenation of some
  958.       strings and components $a and    $b.  If    these components use
  959.       overloading, the catenation operator will look for an
  960.       overloaded operator ., if not    present, it will look for an
  961.       overloaded operator "".  Thus    it is enough to    use
  962.  
  963.         use    overload nomethod => \&wrap, '""' => \&str;
  964.         sub    str {
  965.           my ($meth, $a, $b) = @{+shift};
  966.           $a = 'u' unless defined $a;
  967.           $b = 'u' unless defined $b;
  968.           "[$meth $a $b]";
  969.         }
  970.  
  971.       Now one can change the last line of the script to
  972.  
  973.         print "side    = $side\n";
  974.  
  975.       which    outputs
  976.  
  977.         side = [/ [- [sqrt [+ 1 [**    [n 1 u]    2]] u] 1] [n 1 u]]
  978.  
  979.       and one can inspect the value    in debugger using all the
  980.       possible methods.
  981.  
  982.       Something is is still    amiss: consider    the loop variable $cnt
  983.       of the script.  It was a number, not an object.  We cannot
  984.  
  985.  
  986.  
  987.      Page 15                        (printed 10/23/98)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  995.  
  996.  
  997.  
  998.       make this value of type symbolic, since then the loop    will
  999.       not terminate.
  1000.  
  1001.       Indeed, to terminate the cycle, the $cnt should become
  1002.       false.  However, the operator    bool for checking falsity is
  1003.       overloaded (this time    via overloaded ""), and    returns    a long
  1004.       string, thus any object of type symbolic is true.  To
  1005.       overcome this, we need a way to compare an object to 0.  In
  1006.       fact,    it is easier to    write a    numeric    conversion routine.
  1007.  
  1008.       Here is the text of _s_y_m_b_o_l_i_c._p_m with such a routine added
  1009.       (and slightly    modifed    _s_t_r()):
  1010.  
  1011.         package symbolic;          # Primitive symbolic calculator
  1012.         use    overload
  1013.           nomethod => \&wrap, '""' => \&str, '0+' => \#
  1014.  
  1015.         sub    new { shift; bless ['n', @_] }
  1016.         sub    wrap {
  1017.           my ($obj,    $other,    $inv, $meth) = @_;
  1018.           ($obj, $other) = ($other,    $obj) if $inv;
  1019.           bless [$meth, $obj, $other];
  1020.         }
  1021.         sub    str {
  1022.           my ($meth, $a, $b) = @{+shift};
  1023.           $a = 'u' unless defined $a;
  1024.           if (defined $b) {
  1025.         "[$meth    $a $b]";
  1026.           }    else {
  1027.         "[$meth    $a]";
  1028.           }
  1029.         }
  1030.         my %subr = ( n => sub {$_[0]},
  1031.              sqrt => sub {sqrt $_[0]},
  1032.              '-' =>    sub {shift() - shift()},
  1033.              '+' =>    sub {shift() + shift()},
  1034.              '/' =>    sub {shift() / shift()},
  1035.              '*' =>    sub {shift() * shift()},
  1036.              '**' => sub {shift() ** shift()},
  1037.                );
  1038.         sub    num {
  1039.           my ($meth, $a, $b) = @{+shift};
  1040.           my $subr = $subr{$meth}
  1041.         or die "Do not know how    to ($meth) in symbolic";
  1042.           $a = $a->num if ref $a eq    __PACKAGE__;
  1043.           $b = $b->num if ref $b eq    __PACKAGE__;
  1044.           $subr->($a,$b);
  1045.         }
  1046.  
  1047.       All the work of numeric conversion is    done in    %subr and
  1048.       _n_u_m().  Of course, %subr is not complete, it contains    only
  1049.       operators used in teh    example    below.    Here is    the extra-
  1050.  
  1051.  
  1052.  
  1053.      Page 16                        (printed 10/23/98)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  1061.  
  1062.  
  1063.  
  1064.       credit question: why do we need an explicit recursion    in
  1065.       _n_u_m()?  (Answer is at    the end    of this    section.)
  1066.  
  1067.       Use this module like this:
  1068.  
  1069.         require symbolic;
  1070.         my $iter = new symbolic 2;      # 16-gon
  1071.         my $side = new symbolic 1;
  1072.         my $cnt = $iter;
  1073.  
  1074.         while ($cnt) {
  1075.           $cnt = $cnt - 1;          # Mutator `--' not implemented
  1076.           $side = (sqrt(1 +    $side**2) - 1)/$side;
  1077.         }
  1078.         printf "%s=%f\n", $side, $side;
  1079.         printf "pi=%f\n", $side*(2**($iter+2));
  1080.  
  1081.       It prints (without so    many line breaks)
  1082.  
  1083.         [/ [- [sqrt    [+ 1 [** [/ [- [sqrt [+    1 [** [n 1] 2]]] 1]
  1084.                     [n 1]] 2]]]    1]
  1085.            [/ [- [sqrt [+ 1    [** [n 1] 2]]] 1] [n 1]]]=0.198912
  1086.         pi=3.182598
  1087.  
  1088.       The above module is very primitive.  It does not implement
  1089.       mutator methods (++, -= and so on), does not do deep copying
  1090.       (not required    without    mutators!), and    implements only    those
  1091.       arithmetic operations    which are used in the example.
  1092.  
  1093.       To implement most arithmetic operattions is easy, one    should
  1094.       just use the tables of operations, and change    the code which
  1095.       fills    %subr to
  1096.  
  1097.         my %subr = ( 'n' =>    sub {$_[0]} );
  1098.         foreach my $op (split " ", $overload::ops{with_assign}) {
  1099.           $subr{$op} = $subr{"$op="} = eval    "sub {shift() $op shift()}";
  1100.         }
  1101.         my @bins = qw(binary 3way_comparison num_comparison    str_comparison);
  1102.         foreach my $op (split " ", "@overload::ops{    @bins }") {
  1103.           $subr{$op} = eval    "sub {shift() $op shift()}";
  1104.         }
  1105.         foreach my $op (split " ", "@overload::ops{qw(unary    func)}") {
  1106.           print "defining `$op'\n";
  1107.           $subr{$op} = eval    "sub {$op shift()}";
  1108.         }
  1109.  
  1110.       Due to the section on    _C_a_l_l_i_n_g    _C_o_n_v_e_n_t_i_o_n_s _f_o_r    _M_u_t_a_t_o_r_s, we
  1111.       do not need anything special to make += and friends work,
  1112.       except filling += entry of %subr, and    defining a copy
  1113.       constructor (needed since Perl has no    way to know that the
  1114.       implementation of '+=' does not mutate the argument, compare
  1115.       the section on _C_o_p_y _C_o_n_s_t_r_u_c_t_o_r).
  1116.  
  1117.  
  1118.  
  1119.      Page 17                        (printed 10/23/98)
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  1127.  
  1128.  
  1129.  
  1130.       To implement a copy constructor, add '=' = \&cpy> to use
  1131.       overload line, and code (this    code assumes that mutators
  1132.       change things    one level deep only, so    recursive copying is
  1133.       not needed):
  1134.  
  1135.         sub    cpy {
  1136.           my $self = shift;
  1137.           bless [@$self], ref $self;
  1138.         }
  1139.  
  1140.       To make ++ and -- work, we need to implement actual
  1141.       mutators, either directly, or    in nomethod.  We continue to
  1142.       do things inside nomethod, thus add
  1143.  
  1144.           if ($meth    eq '++'    or $meth eq '--') {
  1145.         @$obj =    ($meth,    (bless [@$obj]), 1); # Avoid circular reference
  1146.         return $obj;
  1147.           }
  1148.  
  1149.       after    the first line of _w_r_a_p().  This    is not a most
  1150.       effective implementation, one    may consider
  1151.  
  1152.         sub    inc { $_[0] = bless ['++', shift, 1]; }
  1153.  
  1154.       instead.
  1155.  
  1156.       As a final remark, note that one can fill %subr by
  1157.  
  1158.         my %subr = ( 'n' =>    sub {$_[0]} );
  1159.         foreach my $op (split " ", $overload::ops{with_assign}) {
  1160.           $subr{$op} = $subr{"$op="} = eval    "sub {shift() $op shift()}";
  1161.         }
  1162.         my @bins = qw(binary 3way_comparison num_comparison    str_comparison);
  1163.         foreach my $op (split " ", "@overload::ops{    @bins }") {
  1164.           $subr{$op} = eval    "sub {shift() $op shift()}";
  1165.         }
  1166.         foreach my $op (split " ", "@overload::ops{qw(unary    func)}") {
  1167.           $subr{$op} = eval    "sub {$op shift()}";
  1168.         }
  1169.         $subr{'++'}    = $subr{'+'};
  1170.         $subr{'--'}    = $subr{'-'};
  1171.  
  1172.       This finishes    implementation of a primitive symbolic
  1173.       calculator in    50 lines of Perl code.    Since the numeric
  1174.       values of subexpressions are not cached, the calculator is
  1175.       very slow.
  1176.  
  1177.       Here is the answer for the exercise: In the case of _s_t_r(),
  1178.       we need no explicit recursion    since the overloaded
  1179.       .-operator will fall back to an existing overloaded operator
  1180.       "".  Overloaded arithmetic operators _d_o _n_o_t fall back    to
  1181.       numeric conversion if    fallback is not    explicitly requested.
  1182.  
  1183.  
  1184.  
  1185.      Page 18                        (printed 10/23/98)
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  1193.  
  1194.  
  1195.  
  1196.       Thus without an explicit recursion _n_u_m() would convert ['+',
  1197.       $a, $b] to $a    + $b, which would just rebuild the argument of
  1198.       _n_u_m().
  1199.  
  1200.       If you wonder    why defaults for conversion are    different for
  1201.       _s_t_r()    and _n_u_m(), note    how easy it was    to write the symbolic
  1202.       calculator.  This simplicity is due to an appropriate    choice
  1203.       of defaults.    One extra note:    due to teh explicit recursion
  1204.       _n_u_m()    is more    fragile    than _s_y_m():  we    need to    explicitly
  1205.       check    for the    type of    $a and $b.  If componets $a and    $b
  1206.       happen to be of some related type, this may lead to
  1207.       problems.
  1208.  
  1209.       _R_e_a_l_l_y symbolic calculator
  1210.  
  1211.       One may wonder why we    call the above calculator symbolic.
  1212.       The reason is    that the actual    calculation of the value of
  1213.       expression is    postponed until    the value is _u_s_e_d.
  1214.  
  1215.       To see it in action, add a method
  1216.  
  1217.         sub    STORE {
  1218.           my $obj =    shift;
  1219.           $#$obj = 1;
  1220.           @$obj->[0,1] = ('=', shift);
  1221.         }
  1222.  
  1223.       to the package symbolic.  After this change one can do
  1224.  
  1225.         my $a = new    symbolic 3;
  1226.         my $b = new    symbolic 4;
  1227.         my $c = sqrt($a**2 + $b**2);
  1228.  
  1229.       and the numeric value    of $c becomes 5.  However, after
  1230.       calling
  1231.  
  1232.         $a->STORE(12);  $b->STORE(5);
  1233.  
  1234.       the numeric value of $c becomes 13.  There is    no doubt now
  1235.       that the module symbolic provides a _s_y_m_b_o_l_i_c calculator
  1236.       indeed.
  1237.  
  1238.       To hide the rough edges under    the hood, provide a _t_i_e()d
  1239.       interface to the package symbolic (compare with the section
  1240.       on _M_e_t_a_p_h_o_r _c_l_a_s_h).  Add methods
  1241.  
  1242.         sub    TIESCALAR { my $pack = shift; $pack->new(@_) }
  1243.         sub    FETCH {    shift }
  1244.         sub    nop {  }      # Around a bug
  1245.  
  1246.       (the bug is described    in the section on _B_U_G_S).  One can use
  1247.       this new interface as
  1248.  
  1249.  
  1250.  
  1251.      Page 19                        (printed 10/23/98)
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  1259.  
  1260.  
  1261.  
  1262.         tie    $a, 'symbolic',    3;
  1263.         tie    $b, 'symbolic',    4;
  1264.         $a->nop;  $b->nop;      # Around a bug
  1265.  
  1266.         my $c = sqrt($a**2 + $b**2);
  1267.  
  1268.       Now numeric value of $c is 5.     After $a = 12;    $b = 5 the
  1269.       numeric value    of $c becomes 13.  To insulate the user    of the
  1270.       module add a method
  1271.  
  1272.         sub    vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
  1273.  
  1274.       Now
  1275.  
  1276.         my ($a, $b);
  1277.         symbolic->vars($a, $b);
  1278.         my $c = sqrt($a**2 + $b**2);
  1279.  
  1280.         $a = 3; $b = 4;
  1281.         printf "c5    %s=%f\n", $c, $c;
  1282.  
  1283.         $a = 12; $b    = 5;
  1284.         printf "c13     %s=%f\n", $c, $c;
  1285.  
  1286.       shows    that the numeric value of $c follows changes to    the
  1287.       values of $a and $b.
  1288.  
  1289.      AAAAUUUUTTTTHHHHOOOORRRR
  1290.       Ilya Zakharevich <_i_l_y_a@_m_a_t_h._m_p_s._o_h_i_o-_s_t_a_t_e._e_d_u>.
  1291.  
  1292.      DDDDIIIIAAAAGGGGNNNNOOOOSSSSTTTTIIIICCCCSSSS
  1293.       When Perl is run with    the ----DDDDoooo    switch or its equivalent,
  1294.       overloading induces diagnostic messages.
  1295.  
  1296.       Using    the m command of Perl debugger (see the    _p_e_r_l_d_e_b_u_g
  1297.       manpage) one can deduce which    operations are overloaded (and
  1298.       which    ancestor triggers this overloading). Say, if eq    is
  1299.       overloaded, then the method (eq is shown by debugger.    The
  1300.       method () corresponds    to the fallback    key (in    fact a
  1301.       presence of this method shows    that this package has
  1302.       overloading enabled, and it is what is used by the
  1303.       Overloaded function of module    overload).
  1304.  
  1305.      BBBBUUUUGGGGSSSS
  1306.       Because it is    used for overloading, the per-package hash
  1307.       %OVERLOAD now    has a special meaning in Perl. The symbol
  1308.       table    is filled with names looking like line-noise.
  1309.  
  1310.       For the purpose of inheritance every overloaded package
  1311.       behaves as if    fallback is present (possibly undefined). This
  1312.       may create interesting effects if some package is not
  1313.       overloaded, but inherits from    two overloaded packages.
  1314.  
  1315.  
  1316.  
  1317.      Page 20                        (printed 10/23/98)
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  1325.  
  1326.  
  1327.  
  1328.       Relation between overloading and _t_i_e()ing is broken.
  1329.       Overloading is triggered or not basing on the    _p_r_e_v_i_o_u_s class
  1330.       of _t_i_e()d value.
  1331.  
  1332.       This happens because the presence of overloading is checked
  1333.       too early, before any    _t_i_e()d access is attempted.  If    the
  1334.       _F_E_T_C_H()ed class of the _t_i_e()d    value does not change, a
  1335.       simple workaround is to access the value immediately after
  1336.       _t_i_e()ing, so that after this call the    _p_r_e_v_i_o_u_s class
  1337.       coincides with the current one.
  1338.  
  1339.       NNNNeeeeeeeeddddeeeedddd:::: a way    to fix this without a speed penalty.
  1340.  
  1341.       Barewords are    not covered by overloaded string constants.
  1342.  
  1343.       This document    is confusing.  There are grammos and
  1344.       misleading language used in places.  It would    seem a total
  1345.       rewrite is needed.
  1346.  
  1347.  
  1348.  
  1349.  
  1350.  
  1351.  
  1352.  
  1353.  
  1354.  
  1355.  
  1356.  
  1357.  
  1358.  
  1359.  
  1360.  
  1361.  
  1362.  
  1363.  
  1364.  
  1365.  
  1366.  
  1367.  
  1368.  
  1369.  
  1370.  
  1371.  
  1372.  
  1373.  
  1374.  
  1375.  
  1376.  
  1377.  
  1378.  
  1379.  
  1380.  
  1381.  
  1382.  
  1383.      Page 21                        (printed 10/23/98)
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.      oooovvvveeeerrrrllllooooaaaadddd((((3333))))      1111////AAAAuuuugggg////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       oooovvvveeeerrrrllllooooaaaadddd((((3333))))
  1391.  
  1392.  
  1393.  
  1394.  
  1395.  
  1396.  
  1397.  
  1398.  
  1399.  
  1400.  
  1401.  
  1402.  
  1403.  
  1404.  
  1405.  
  1406.  
  1407.  
  1408.  
  1409.  
  1410.  
  1411.  
  1412.  
  1413.  
  1414.  
  1415.  
  1416.  
  1417.  
  1418.  
  1419.  
  1420.  
  1421.  
  1422.  
  1423.  
  1424.  
  1425.  
  1426.  
  1427.  
  1428.  
  1429.  
  1430.  
  1431.  
  1432.  
  1433.  
  1434.  
  1435.  
  1436.  
  1437.  
  1438.  
  1439.  
  1440.  
  1441.  
  1442.  
  1443.  
  1444.  
  1445.  
  1446.      Page 22                        (printed 10/23/98)
  1447.  
  1448.  
  1449.  
  1450.  
  1451.  
  1452.  
  1453.